package cc.cix.hq.org.controller;

import cc.cix.hq.common.core.entity.org.LoginLog;
import cc.cix.hq.common.core.utils.HqUtil;
import cc.cix.hq.org.service.ILoginLogService;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cix
 */
@Api(tags = "首页管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/index")
public class IndexController {

    private final ILoginLogService loginLogService;

    @ApiOperation("首页")
    @GetMapping("/index")
    public Map<String, Object> index() {
        // 获取总访问次数
        Long totalVisitCount = loginLogService.count();

        // 获取今日访问次数
        Long todayVisitCount = loginLogService.lambdaQuery()
                .between(LoginLog::getLoginTime, DateUtil.today(), DateUtil.today())
                .count();

        // 获取今日访问 IP 数
        Long todayIp = loginLogService.lambdaQuery()
                .between(LoginLog::getLoginTime, DateUtil.today(), DateUtil.today())
                .groupBy(LoginLog::getIp)
                .count();

        // 获取近10天访问记录
        List<LoginLog> lastTenVisitCount = loginLogService.lambdaQuery()
                .between(LoginLog::getLoginTime, DateUtil.offsetDay(DateUtil.date(), 10), DateUtil.date())
                .list();

        // 获取近10天当前用户的访问记录
        List<LoginLog> lastTenUserVisitCount = loginLogService.lambdaQuery()
                .eq(LoginLog::getUsername, HqUtil.getCurrentUser().getUsername())
                .between(LoginLog::getLoginTime, DateUtil.offsetDay(DateUtil.date(), 10), DateUtil.date())
                .list();

        Map<String, Object> data = new HashMap<>(5);
        data.put("totalVisitCount", totalVisitCount);
        data.put("todayVisitCount", todayVisitCount);
        data.put("todayIp", todayIp);
        data.put("lastTenVisitCount", lastTenVisitCount);
        data.put("lastTenUserVisitCount", lastTenUserVisitCount);
        return data;
    }

}
